package com.xyz.jira.plugin;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.project.Project;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.xyz.jira.plugin.responses.IssueTypesInfo;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * A resource of message.
 */
@Path("/issueTypes")
public class IssueTypes {

	/**
	 * Gets a listing of issue types available for a project.
	 * 
	 * @param pid
	 *            Project id for which to get the issue types
	 * @return the message from the key parameter or the default message
	 */
	@GET
	@AnonymousAllowed
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getIssueTypes(@QueryParam("pid") String pid) {
		long projectId = -1;

		if (pid.length() > 0) {
			// Load the project issues by id
			try {
				projectId = Long.parseLong(pid);
				Project project = ComponentManager.getInstance()
						.getProjectManager().getProjectObj(projectId);
				return Response.ok(
						new IssueTypesInfo(pid, project.getIssueTypes()))
						.build();
			} catch (NumberFormatException nfe) {
				// Ignore number format error, the pid can be the project key also
				// Load the project issues by key
				Project project = ComponentManager.getInstance()
						.getProjectManager().getProjectObjByKey(pid);
				return Response.ok(
						new IssueTypesInfo(pid, project.getIssueTypes()))
						.build();
			}
		} else {
			return Response.ok(new IssueTypesInfo("No pid provided", null))
					.build();
		}
	} 
}